import $ from "jquery";
import Store from "store2";
import formTpl from "../components/orderForm/index.ejs";

(($) => {
  let params = {
    people: Store.get("people"),
    restaurant: Store.get("restaurant"),
    meal: Store.get("meal"),
  };

  const methods = {
    bindMealEvent: (selector) => {
      $(selector).on("click", function () {
        const { id } = $(this).data();
        location.href = `list.html?type=restaurant&id=${id}`;
      });
    },

    bindSubmitEvent: (selector) => {
      $(selector).on("submit", function () {
        const { people, restaurant = {}, meal = {} } = params;
        const data = Store.get("data") || [];
        const _data = data.concat([
          {
            person: people,
            restaurant: restaurant.value,
            meal: meal.meal,
            price: meal.price,
            sum: meal.sum,
          },
        ]);
        Store.set("data", _data);
        Store.has("people") && Store.remove("people");
        Store.has("restaurant") && Store.remove("restaurant");
        Store.has("meal") && Store.remove("meal");
      });
    },

    renderView: (selector) => {
      const { people, restaurant, meal = {} } = params;
      const formEl = formTpl({
        people,
        restaurant,
        package: meal ? meal.meal : "",
      });
      $(selector).append(formEl);
      methods.bindMealEvent("#package");
      methods.bindSubmitEvent("form");
    },
  };

  methods.renderView("body");
})($);
